package com.lg.zk.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ZookeeperProSync implements Watcher {
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static ZooKeeper zkClient = null;
    private static Stat stat = new Stat();
    private static boolean switchFlag;

    public static void main(String[] args) throws Exception {
        String path = "/username";
        Watcher watcher;
        zkClient = new ZooKeeper("127.0.0.1:2128", 5000, new ZookeeperProSync());

        countDownLatch.await();

        System.out.println(new String(zkClient.getData(path, true, stat)));

        TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
    }

    @Override
    public void process(WatchedEvent event) {
        if (event.getType() == Event.EventType.None && event.getPath() == null) {
            countDownLatch.countDown();
        } else if (event.getType() == Event.EventType.NodeDataChanged) {
            try {
                log.info("watcher 触发。。。,配置已经修改，新值为："+new String(zkClient.getData(event.getPath(),true, stat)));
            } catch (KeeperException | InterruptedException e) {
                e.printStackTrace();
            }
            countDownLatch.countDown();
        }

    }
}
